/******************************************************************************
 *
 * Project:		mGameEngine
 * File:		tcpconnection.h
 * Author:		karooolek
 * Created on:	2009-03-14
 *
 ******************************************************************************/

#ifndef TCPCONNECTION_H_
#define TCPCONNECTION_H_

#include "ipconnection.h"
#include <string.h>
#include <stdio.h>
#include "Log.h"
#include <sstream>


#define DEFAULT_TIMEOUT 30000		// milisec
#define TIME_INTERVAL 500			// polling time interval


/**
 * TCP/IP connection.
 * Network connection with another machine over TCP/IP stream protocol.
 * Connection is established between exactly two machines.
 * When server opens connection, it must wait until client connects.
 * Using TCP/IP protocol guarantees 100% of correct data transmission
 * unless connection is lost.
 */
class TCPConnection : public IPConnection
{
public:
	/**
	 * Create new TCP/IPconnection.
	 */
	TCPConnection();

	/**
	 * Create new TCP/IP connection with specified address.
	 * @param ipaddr IP address.
	 */
	TCPConnection(const IPAddress &ipaddr);

	/**
	 * Destroy TCP/IP connection.
	 */
	~TCPConnection();

	/**
	 * Open TCP/IP connection..
	 */
	void open();

	/**
	 * Close TCP/IP connection.
	 */
	void close();

	/**
	 * Connect to TCP/IP connection server.
	 */
	void connect();

	/**
	 * Disconnect from TCP/IP connection server.
	 */
	void disconnect();

	/**
	 * Send data to another machine using TCP/IP protocol
	 * @param data data to be sent.
	 * @param size data size.
	 * @return number of sent bytes os 0 if connection was lost.
	 */
	virtual uint send(const uint8 *data, uint size);

	/**
	 * Receive data from another machine.
	 * @param buffer buffer to store received data.
	 * @param size buffer size.
	 * @return number of received bytes or 0 if connection was lost.
	 */
	virtual uint receive(uint8 *buffer, uint size);

	/*
	 * Return timeout, which is set for receiving and
	 * connecting.
	 */
	int getTimeout() const { return _timeout;	}

	/*
	 * Sets new timeout.
	 * @param timeout value of new timeout in milisecs.
	 */
	void setTimeout(int timeout) { _timeout = timeout; }

private:
	int _timeout;
	fd_set readfds;
	struct timeval tv;
public:
	void _sleep(int milisec) {
		tv.tv_sec = 0;
		tv.tv_usec = milisec * 1000;
		if (milisec >= 0)
			select(0, NULL, NULL, NULL, &tv);			// sleep
		else
			select(0, NULL, NULL, NULL, NULL);			// sleep for ever
	}
};


#endif // TCPCONNECTION_H_
